@file:Suppress("DEPRECATION")

package com.boyou.sytzc.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatSpinner
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.activity.viewModels
import com.baidu.location.BDLocation
import com.boyou.sytzc.R
import com.boyou.sytzc.api.vmodel.HttpApiViewModel
import com.boyou.sytzc.core.appctx.AppData
import com.boyou.sytzc.data.database.CarNoOrRouteNoDB
import com.boyou.sytzc.data.database.table.CarNoOrRouteNoInfo
import com.boyou.sytzc.data.entity.NewsInfoEntity
import com.boyou.sytzc.data.event.DeviceNoChangedEvent
import com.boyou.sytzc.databinding.ActivityMainBinding
import com.boyou.sytzc.core.appctx.AppApplication
import com.boyou.sytzc.core.appctx.AppJump
import com.boyou.sytzc.core.service.UploadService
import com.boyou.sytzc.core.service.LocationService
import com.boyou.sytzc.utils.app.AppConfig
import com.boyou.sytzc.utils.common.CommonUtil
import com.boyou.sytzc.utils.database.RecordDbHelper
import com.boyou.sytzc.utils.io.isNetworkAvailable
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hi.dhl.binding.viewbind
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.yuge.yugecse.data.event.ActivityFinishEvent
import com.yuge.yugecse.ext.uibasic.BasicActivity
import com.yuge.yugecse.util.device.ToastUtil
import com.yuge.yugecse.util.generic.ActivityUtil
import com.yuge.yugecse.util.generic.ApkUtil
import org.simple.eventbus.EventBus
import org.simple.eventbus.Subscriber

/** 程序主入口   */
class MainActivity : BasicActivity(), AdapterView.OnItemSelectedListener {

    private val binding by viewbind<ActivityMainBinding>()

    private val networkViewModel by viewModels<HttpApiViewModel>()
    private val appConfig by lazy { AppConfig.singleton() }
    private val recorderDBHelper by lazy { RecordDbHelper.getInstance(this) }
    private val carNoOrRouteDb by lazy { CarNoOrRouteNoDB.singleton() }

    private var exitTime: Long = 0

    @SuppressLint("SetTextI18n")
    @Suppress("UNCHECKED_CAST")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(binding) {
            txtSettings.setOnClickListener {
                ActivityUtil.goForward(
                    this@MainActivity,
                    SettingsActivity::class.java,
                    false
                )
            }
            txtGetData.setOnClickListener { showReloadDataDialog() }
            aspDriverNo.onItemSelectedListener = this@MainActivity
            txtVersionName.text = "版本：${ApkUtil.getVersionName(me)}"
        }
        EventBus.getDefault().register(this)
        requestRuntimePermission() //请求应用运行时权限
    }

    /** 请求应用运行时权限 **/
    private fun requestRuntimePermission() = XXPermissions.with(this)
        .permission(
            Permission.READ_PHONE_STATE,
            Permission.WRITE_EXTERNAL_STORAGE,
            Permission.ACCESS_COARSE_LOCATION,
            Permission.ACCESS_FINE_LOCATION,
            Permission.CAMERA
        )
        .request { _, all ->
            if (all) initMainActivity()
            else ToastUtil.showGenericToast(this, "应用未开启必要权限，部分功能收到影响")
        }

    /** 初始化MainActivity **/
    private fun initMainActivity() {
        try {
            if (!CommonUtil.initApplication(me)) {
                //初始化程序,检测内存
                ToastUtil.showGenericToast(me, "内存设备检测失败，无法使用应用，正在退出应用!")
                ActivityUtil.goBack(me)
                return
            }
        } catch (e: Exception) {
            e.printStackTrace()
            ToastUtil.showGenericToast(me, "内存设备检测失败，无法使用应用，正在退出应用!")
            ActivityUtil.goBack(me)
            return
        }
        CommonUtil.clearCache() //清理数据
        when (AppApplication.deviceNoManager.isAppFirstExec) {
            true -> startActivityForResult(Intent(this, InitSettingsActivity::class.java).apply {
                putExtra("deviceNo", AppApplication.deviceNoManager.deviceNo ?: "")
            }, 0x000000B)
            else -> {
                if (!AppApplication.deviceNoManager.isDeviceNoEnabled) {
                    startActivityForResult(Intent(this, SettingsActivity::class.java), 0x000000A)
                    return
                }
                loadConfigInfo() //加载配置信息
                getCodeFromServer() //获取车辆信息与线路问题
                getDriverNoFromServer() //更新司机编号信息
                getDeviceTipInformation() //获取新闻列表
            }
        }
    }

    /** 加载配置信息 **/
    @SuppressLint("SetTextI18n")
    private fun loadConfigInfo() {
        binding.txtDeviceID.text = "设备ID：${AppApplication.deviceNoManager.deviceNo ?: "---"}"
        //启动定位和上传服务
        startService(Intent(me, LocationService::class.java))
        startService(Intent(me, UploadService::class.java))
    }

    fun onViewClick(view: View) {
        when (view.id) {
            R.id.txtDataUpgrade -> getDriverNoFromServer(true)
            R.id.txtGetData -> showReloadDataDialog()
            R.id.txtSettings ->
                startActivityForResult(Intent(this, SettingsActivity::class.java), 0x0010)
            R.id.txtDataView -> ActivityUtil.goForward(me, RecordListActivity::class.java, false)
            R.id.imgExcavator -> AppJump.go2takeCameraActivity(this, 0, "渣车模式")
            R.id.imgTruck -> AppJump.go2takeCameraActivity(this, 1, "计时模式")
        }
    }

    override fun onNothingSelected(parent: AdapterView<*>?) {}

    override fun onItemSelected(parent: AdapterView<*>?, view: View?, posn: Int, id: Long) {
        appConfig.driverNoData = parent?.getItemAtPosition(posn)?.toString() ?: ""
    }


    @Subscriber
    fun onDeviceNoChangedEvent(event: DeviceNoChangedEvent) {
        loadConfigInfo() //加载配置信息
    }

    override fun onFinishActivity(event: ActivityFinishEvent) {
        super.onFinishActivity(event)
        ActivityUtil.abortExit()//终止应用程序
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            0x0010 -> getCodeFromServer(false)
            0x000000A -> if (resultCode == Activity.RESULT_OK) loadConfigInfo() //加载配置信息
            0x000000B -> if (resultCode == Activity.RESULT_OK) {
                loadConfigInfo() //加载配置信息
                getDeviceTipInformation() //获取新闻列表
            }
        }
    }

    override fun onBackPressed() {
        val nowTime = System.currentTimeMillis()
        if (nowTime - exitTime > 800) {
            exitTime = nowTime
            ToastUtil.showGenericToast(me, "再按一次退出应用")
            return
        }
        EventBus.getDefault().post(ActivityFinishEvent())
    }

    /** 显示是否获取新数据的提示框  **/
    private fun showReloadDataDialog(): Unit = with(AlertDialog.Builder(this)
        .setMessage("是否重新获取数据？")
        .setNegativeButton("取消", null)
        .setPositiveButton("获取最新数据") { _, _ -> getCodeFromServer() }
        .create()) {
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        show()
    }

    @SuppressLint("SetTextI18n")
    @Subscriber
    fun onReceiveLocationEvent(bdLocation: BDLocation) {
        binding.txtLocation.text = when {
            TextUtils.isEmpty(bdLocation.address.address) -> "位置: 获取中..."
            else -> bdLocation.addrStr
        }
    }

    override fun onDestroy() {
        stopService(Intent(me, UploadService::class.java))//关闭后台上传服务
        stopService(Intent(me, LocationService::class.java))//关闭后台定位服务
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    /** 获取设备提示信息 **/
    private fun getDeviceTipInformation() {
        val gotoNewsInfoActivity: (newsInfoList: ArrayList<NewsInfoEntity>) -> Unit = { data ->
            startActivity(Intent(this, NewsInfoActivity::class.java).apply {
                putParcelableArrayListExtra("newsInfos", data)
            })
        }
        when (isNetworkAvailable()) {
            true -> networkViewModel.validateDeviceNo(AppApplication.deviceNoManager.deviceNo) { isSuccessful, _, result ->
                if (isSuccessful && result != null && result.isNotEmpty()) {
                    gotoNewsInfoActivity(arrayListOf(*(result.toTypedArray())))
                }
            }
            else -> if (!recorderDBHelper.isUploadedIn5Days(AppApplication.deviceNoManager.deviceNo)) {
                val newsInfoList = arrayListOf(
                    NewsInfoEntity("#ffff0000", "您的设备号未注册"),
                    NewsInfoEntity("#ff333333", "请联系服务商：重庆宏道拓土科技有限公司"),
                    NewsInfoEntity("#ff333333", "联系电话：13368136787")
                )
                gotoNewsInfoActivity(newsInfoList)
            }
        }

    }


    /** 从服务器获取编号信息  */
    @Suppress("DEPRECATION")
    private fun getCodeFromServer(showLoadingDialog: Boolean = true) {
        var loadingDialog: ProgressDialog? = null
        if (showLoadingDialog) {
            loadingDialog = ProgressDialog(this).apply {
                setCancelable(false)
                setCanceledOnTouchOutside(false)
                setMessage("正在获取挖机编号和线路编号...")
                show()
            }
        }
        val hideProgressDialog: () -> Unit = {
            if (loadingDialog?.isShowing == true) {
                loadingDialog.dismiss()
            }
        }
        networkViewModel.getCode { isOk, message, info ->
            if (showLoadingDialog) hideProgressDialog()
            if (isOk) {
                carNoOrRouteDb.clear()
                if (!info?.car.isNullOrEmpty()) {
                    val dataSource = info!!.car!!.map { CarNoOrRouteNoInfo(name = it, type = 0) }
                    carNoOrRouteDb.put(dataSource)
                }
                if (!info?.line.isNullOrEmpty()) {
                    val dataSource = info!!.line!!.map { CarNoOrRouteNoInfo(name = it, type = 1) }
                    carNoOrRouteDb.put(dataSource)
                }
                if (showLoadingDialog) ToastUtil.showGenericToast(this@MainActivity, "编号信息已获取完成")
            } else {
                if (showLoadingDialog) when (info?.code != null) {
                    true -> ToastUtil.showGenericToast(
                        this@MainActivity,
                        resources.getIdentifier("getCodeErr_${info!!.code}", "string", packageName)
                    )
                    else -> ToastUtil.showGenericToast(this@MainActivity, message)
                }
            }
        }
    }

    /**
     * 从服务器获取司机编号
     * @param isHandleToUpdate 是否手动处理更新
     */
    private fun getDriverNoFromServer(isHandleToUpdate: Boolean = false) {

        /**
         * 处理司机编号的状况
         * @param jsNos 司机编号数组
         */
        fun dealDriverNoSituation(jsNos: Array<String>?) {
            val aspDriverNo = me.findViewById(R.id.aspDriverNo) as AppCompatSpinner
            aspDriverNo.adapter = ArrayAdapter(
                this@MainActivity, R.layout.item_for_spinner_drop_list, android.R.id.text1, jsNos
                    ?: arrayOf()
            )
            val sjSelectedIndex = jsNos?.indexOf(appConfig.driverNoData)
                ?: -1
            if (jsNos?.isNotEmpty() == true) {
                val curSelectedIndex = if (sjSelectedIndex != -1) sjSelectedIndex else 0
                aspDriverNo.setSelection(curSelectedIndex, true)
                appConfig.driverNoData = jsNos[curSelectedIndex]
            } else {
                appConfig.driverNoData = ""
            }
        }

        if (!isHandleToUpdate && appConfig.driverNoData.isNotEmpty()) {
            val baseDataJsonStr = appConfig.driverNoData
            if (!TextUtils.isEmpty(baseDataJsonStr)) {
                val baseDataJsonObj = try {
                    Gson().fromJson(baseDataJsonStr, object : TypeToken<Array<String>>() {}.type)
                } catch (e: Exception) {
                    e.printStackTrace()
                    arrayOf(baseDataJsonStr)
                }
                dealDriverNoSituation(baseDataJsonObj)
            }
            return
        }
        @Suppress("DEPRECATION")
        with(ProgressDialog(this)) {
            this.let {
                setCancelable(false)
                setCanceledOnTouchOutside(false)
                setMessage("正在获取司机编号...")
                show()
            }

            fun hideProgressDialog() = try {
                this.let {
                    if (isShowing)
                        dismiss()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

            networkViewModel.getDriverNoInfo { isOk, msg, info ->
                hideProgressDialog()
                if (isOk) {
                    appConfig.driverNoData = Gson().toJson(info?.sj ?: listOf<String>())
                    dealDriverNoSituation(info?.sj?.toTypedArray())
                    ToastUtil.showGenericToast(this@MainActivity, "司机编号信息已获取完成")
                } else {
                    if (info?.code != null) ToastUtil.showGenericToast(
                        this@MainActivity,
                        resources.getIdentifier("getCodeErr_${info.code}", "string", packageName)
                    )
                    else ToastUtil.showGenericToast(this@MainActivity, msg)
                }
            }
        }
    }

}